﻿/*
* Copyright (c) 2010-2012 Tesla Engine Group
* 
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
* 
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
* 
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/

using System;
using Tesla.Content;
using Tesla.Core;
using Tesla.Graphics.Implementation;

namespace Tesla.Graphics {
    /// <summary>
    /// SamplerState object that controls how a texture is sampled.
    /// </summary>
    public class SamplerState : RenderState {
        private SamplerStateImplementation _impl;
        private RenderStateKey _key;

        /// <summary>
        /// Gets the built-in state object where point filtering is used and UVW coordinates wrap.
        /// </summary>
        public static SamplerState PointWrap {
            get;
            internal set;
        }

        /// <summary>
        /// Gets the built-in state object where point filtering is used and UVW coordinates are clamped to [0, 1]. This
        /// is the default state.
        /// </summary>
        public static SamplerState PointClamp {
            get;
            internal set;
        }

        /// <summary>
        /// Gets the built-in state object where linear filtering is used and UVW coordinates wrap.
        /// </summary>
        public static SamplerState LinearWrap {
            get;
            internal set;
        }

        /// <summary>
        /// Gets the built-in state object where linear filtering is used and UVW coordinates are clamped to [0, 1].
        /// </summary>
        public static SamplerState LinearClamp {
            get;
            internal set;
        }

        /// <summary>
        /// Gets the built-in state object where anisotropic filtering is used and UVW coordinates wrap.
        /// </summary>
        public static SamplerState AnisotropicWrap {
            get;
            internal set;
        }

        /// <summary>
        /// Gets the built-in state object where anisotropic filtering is used and UVW coordinates are
        /// clamped to [0, 1].
        /// </summary>
        public static SamplerState AnisotropicClamp {
            get;
            internal set;
        }

        /// <summary>
        /// Get if this render state has been bound to the pipeline.
        /// </summary>
        public override bool IsBound {
            get {
                return _impl.IsBound;
            }
        }

        /// <summary>
        /// Gets the <see cref="RenderStateKey"/> that is used to compare this state
        /// to another state.
        /// </summary>
        public override RenderStateKey RenderStateKey {
            get {
                if(!_impl.IsBound) {
                    return new RenderStateKey(GetHashCode(), StateType);
                }
                return _key;
            }
        }

        /// <summary>
        /// Get the enumeration describing this render state.
        /// </summary>
        public override RenderStateType StateType {
            get {
                return RenderStateType.SamplerState;
            }
        }

        /// <summary>
        /// Gets the API-specific implementation of this resource.
        /// </summary>
        public override GraphicsResourceImplementation Implementation {
            get {
                return _impl;
            }
        }

        /// <summary>
        /// Gets or sets the addressing mode for the U coordinate. The default value is
        /// <see cref="TextureAddressMode.Clamp"/>.
        /// </summary>
        public TextureAddressMode AddressU {
            get {
                return _impl.AddressU;
            }
            set {
                _impl.AddressU = value;
            }
        }

        /// <summary>
        /// Gets or sets the addressing mode for the V coordinate. The default value is
        /// <see cref="TextureAddressMode.Clamp"/>.
        /// </summary>
        public TextureAddressMode AddressV {
            get {
                return _impl.AddressV;
            }
            set {
                _impl.AddressV = value;
            }
        }

        /// <summary>
        /// Gets or sets the addressing mode for the W coordinate. The default value is
        /// <see cref="TextureAddressMode.Clamp"/>.
        /// </summary>
        public TextureAddressMode AddressW {
            get {
                return _impl.AddressW;
            }
            set {
                _impl.AddressW = value;
            }
        }

        /// <summary>
        /// Gets or sets the filtering method used when sampling a texture. The default value is
        /// <see cref="TextureFilter.Point"/>.
        /// </summary>
        public TextureFilter Filter {
            get {
                return _impl.Filter;
            }
            set {
                _impl.Filter = value;
            }
        }

        /// <summary>
        /// Gets the maximum anisotropy. The default value is four.
        /// </summary>
        public int MaxAnisotropy {
            get {
                return _impl.MaxAnisotropy;
            }
            set {
                _impl.MaxAnisotropy = value;
            }
        }

        /// <summary>
        /// Gets the mipmap LOD bias. The default value is zero.
        /// </summary>
        public float MipMapLevelOfDetailBias {
            get {
                return _impl.MipMapLevelOfDetailBias;
            }
            set {
                _impl.MipMapLevelOfDetailBias = value;
            }
        }

        /// <summary>
        /// Creates a new instance of <see cref="SamplerState"/> with default values.
        /// </summary>
        /// <exception cref="Tesla.Core.TeslaException">Thrown if creating the underlying state implementation fails.</exception>
        public SamplerState() {
            IRenderSystemProvider renderSystem = Engine.Services.GetService<IRenderSystemProvider>();
            if(renderSystem == null) {
                Dispose();
                throw new TeslaException("Render system provider not set, cannot create graphics resource implementation.");
            }

            base.RenderSystem = renderSystem;

            try {
                _impl = renderSystem.CreateSamplerStateImplementation();
            } catch(Exception e) {
                Dispose();
                throw new TeslaException("Error creating underlying implementation, see inner exception for details.", e);
            }

            SetDefaults();
        }

        /// <summary>
        /// Creates a new instance of <see cref="SamplerState"/> with default values.
        /// </summary>
        /// <param name="renderSystem">Render system used to create the underlying implementation.</param>
        /// <exception cref="System.ArgumentNullException">Thrown if the render system is null.</exception>
        /// <exception cref="Tesla.Core.TeslaException">Thrown if creating the underlying state implementation fails.</exception>
        public SamplerState(IRenderSystemProvider renderSystem) {
            if(renderSystem == null) {
                Dispose();
                throw new ArgumentNullException("renderSystem", "Render system cannot be null.");
            }

            base.RenderSystem = renderSystem;

            try {
                _impl = renderSystem.CreateSamplerStateImplementation();
            } catch(Exception e) {
                Dispose();
                throw new TeslaException("Error creating underlying implementation, see inner exception for details.", e);
            }

            SetDefaults();
        }

        /// <summary>
        /// Releases unmanaged resources and performs other cleanup operations before the
        /// <see cref="SamplerState"/> is reclaimed by garbage collection.
        /// </summary>
        ~SamplerState() {
            Dispose(false);
        }

        private void SetDefaults() {
            //Set defaults
            _impl.AddressU = TextureAddressMode.Clamp;
            _impl.AddressV = TextureAddressMode.Clamp;
            _impl.AddressW = TextureAddressMode.Clamp;
            _impl.Filter = TextureFilter.Point;
            _impl.MaxAnisotropy = 4;
            _impl.MipMapLevelOfDetailBias = 0;
        }

        /// <summary>
        /// Binds the render state to the graphics pipeline. This is automatically called the first time the
        /// renderstate is applied or manually called to create the underlying implementation early.
        /// </summary>
        public override void BindRenderState() {
            if(!IsBound) {
                _impl.BindSamplerState();
                _key = new RenderStateKey(GetHashCode(), StateType);
            }
        }

        /// <summary>
        /// Returns a hash code for this instance.
        /// </summary>
        /// <returns>A hash code for this instance.</returns>
        public override int GetHashCode() {
            int hash = StateType.GetHashCode();
            hash = ((hash << 2) - hash) + _impl.AddressU.GetHashCode();
            hash = ((hash << 2) - hash) + _impl.AddressV.GetHashCode();
            hash = ((hash << 2) - hash) + _impl.AddressW.GetHashCode();
            hash = ((hash << 2) - hash) + _impl.Filter.GetHashCode();
            hash = ((hash << 2) - hash) + _impl.MipMapLevelOfDetailBias.GetHashCode();
            hash = ((hash << 2) - hash) + _impl.MaxAnisotropy;
            return hash;
        }

        /// <summary>
        /// Serializes the object and writes it to the output.
        /// </summary>
        /// <param name="output">Savable Output</param>
        public override void Write(ISavableWriter output) {
            output.WriteEnum<TextureAddressMode>("AddressU", _impl.AddressU);
            output.WriteEnum<TextureAddressMode>("AddressV", _impl.AddressV);
            output.WriteEnum<TextureAddressMode>("AddressW", _impl.AddressW);
            output.WriteEnum<TextureFilter>("Filter", _impl.Filter);
            output.Write("MipMapLevelOfDetailBias", _impl.MipMapLevelOfDetailBias);
            output.Write("MaxAnisotropy", _impl.MaxAnisotropy);
        }

        /// <summary>
        /// Deserializes the object and populates it from the input.
        /// </summary>
        /// <param name="input">Savable input</param>
        /// <exception cref="Tesla.Core.TeslaException">Thrown if creating the underlying state implementation fails or the render
        /// system is not set.</exception>
        public override void Read(ISavableReader input) {
            IRenderSystemProvider renderSystem = input.RenderSystem;
            if(renderSystem == null) {
                Dispose();
                throw new TeslaException("Render system provider not set, cannot create graphics resource implementation.");
            }

            base.RenderSystem = renderSystem;
            try {
                _impl = renderSystem.CreateSamplerStateImplementation();
            } catch(Exception e) {
                Dispose();
                throw new TeslaException("Error creating underlying implementation, see inner exception for details.", e);
            }
            _impl.AddressU = input.ReadEnum<TextureAddressMode>();
            _impl.AddressV = input.ReadEnum<TextureAddressMode>();
            _impl.AddressW = input.ReadEnum<TextureAddressMode>();
            _impl.Filter = input.ReadEnum<TextureFilter>();
            _impl.MipMapLevelOfDetailBias = input.ReadSingle();
            _impl.MaxAnisotropy = input.ReadInt();
        }
    }
}
